package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-04-25
 * Time: 16:26
 */
public class TcpEchoClient {
    //此处不用手动给客户端指定端口号,让系统自由分配
    private Socket socket = null;
    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        //调用该方法就会和服务器建立连接
        socket = new Socket(serverIp,serverPort);
    }
    public void start() {
        System.out.println("和服务器连接成功! ");
        Scanner sc = new Scanner(System.in);
        try (InputStream inputStream = socket.getInputStream()) {
            try(OutputStream outputStream = socket.getOutputStream()) {
                while(true) {
                    // 要做的事情,四个步骤
                    // 1.从控制台读字符串
                    System.out.print("-> ");
                    String request = sc.next();
                    // 2.根据读取的字符串,构造请求,把请求发送给服务器
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(request);
                    printWriter.flush();
                    // 3.从服务器读取相应,并解析
                    Scanner respScanner = new Scanner(inputStream);
                    String response = respScanner.next();
                    // 4.把结果显示到控制台
                    System.out.printf("req: %s, resp: %s\n",request,response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }

}
